package com.test.ayi.test.competablefuture;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class CFtest8CompleteOnTimeout {
    // 让时间戳像弹幕一样飞
    private static final DateTimeFormatter TF = DateTimeFormatter.ofPattern("HH:mm:ss");

    public static void main(String[] args) {
        log("我开始等外卖...");
        // 1. 点一份“慢吞吞”的外卖：需要 5 秒
        CompletableFuture.supplyAsync(() -> {
                    log("外卖小哥出门取餐...");
                    int i=1/0;
                    nap(5000);               // 假装路上堵车
                    log("外卖小哥已送达！");
                    return "🦐 麻辣小龙虾一份";
                })
                .completeOnTimeout("怒退外卖！", 3, TimeUnit.SECONDS)
                .exceptionally(e -> "外卖翻车,只能吃泡面了")
                .thenAccept(msg -> log(msg))
                .join();



        // 3. 优雅地关掉线程池（防止厨师赖在厨房不走）
        ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.SECONDS);
    }

    /* ---------- 工具方法 ---------- */
    private static void log(String msg) {
        System.out.printf("%s [%s] %s%n",
                LocalTime.now().format(TF),
                Thread.currentThread().getName(),
                msg);
    }

    private static void nap(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException ignored) {
        }
    }
}
